<?php

/**
 * RabbitCMS
 */
class Page_Models_Page extends Rabbit_Db_Table_Abstract implements Page_Models_Interfaces_Page {

    protected  $_name = 'page';
    public function convert($entity) {
        return new Page_Models_Entities_Page($entity);
    }

    public function getById($id) {
        $row = $this->getAdapter()
					->select()
					->from(array('p' => $this->_name))
					->where('p.id = ?', $id)
					->limit(1)
					->query()
					->fetch();
        return (null == $row) ? null : new Page_Models_Entities_Page($row);
    }

    public function add($page) {
        try {

            $db = $this->getAdapter();
            /**
             * Calculate the right Id
             */
            $parentId = $page->parent_id;
            if ($parentId) {
                $sql = $db->select()->from($this->_name, array('rht'))->where('id = ?', $parentId);
                $right = $db->query($sql)->fetchColumn(0);
            } else {
                $sql = $db->select()->from($this->_name, array('rht' => 'MAX(rht)'));
                $right = $db->query($sql)->fetchColumn(0);
            }

            if ($right != null) {
                //update tree
                $data = array(
                    'lft' => new Zend_Db_Expr('IF (lft >= ' . $db->quote($right) . ', lft + 2, lft)'),
                    'rht' => new Zend_Db_Expr('IF (rht >= ' . $db->quote($right) . ', rht + 2, rht)')
                );
                parent::update($data, null);
                

                $data = array(
                    'name' => $page->name,
                    'slug' => $page->slug,
                    'description' => $page->description,
                    'content' => $page->content,
                    'created_date' => $page->created_date,
                    'num_views' => $page->num_views,
                    'user_id' => $page->user_id,
                    'lft' => $right,
                    'rht' => $right + 1,
                    /**
                     * @since 2.0.8
                     */
                    'language' => $page->language,
                    /**
                     * Added by Tronghm
                     */
                    'meta_title' => $page->meta_title,
                    'meta_desscription' => $page->meta_desscription,
                    'meta_keywords' => $page->meta_keywords,
                );
                if (isset($page->id) && $page->id != null)
                    $data['id'] = $page->id;
                $page = $this->createRow($data);
                $page->save();

                if ($page->id) {
                    return $page->id;
                } else {
                    return false;
                }
                
            }
        } catch (Exception $ex) {
            echo $ex->getMessage();
            return false;
        }
    }

    public function update($page) {
        parent::update(
                array(
                    'name' => $page->name,
                    'slug' => $page->slug,
                    'description' => $page->description,
                    'content' => $page->content,
                    'modified_date' => $page->modified_date,
                    /**
                     * @since 2.0.8
                     */
                    'language' => $page->language,
                ),
                array(
                    'id = ?' => $page->id,
        ));
    }

    public function updateOrder($page) {
        $this->_conn->update($this->_prefix . 'page',
                array(
                    'parent_id' => $page->parent_id,
                    'lft' => $page->lft,
                    'rht' => $page->rht,
                ),
                array(
                    'page_id = ?' => $page->page_id,
        ));
    }

    public function delete($page) {
        
        $this->getAdapter()->delete($this->_prefix . 'page',
                array(
                    'id = ?' => $page->id,
        ));

        $this->getAdapter()->update($this->_prefix . 'page',
                array(
                    'lft' => new Zend_Db_Expr('lft - 1'),
                    'rht' => new Zend_Db_Expr('rht - 1'),
                ),
                array(
                    'lft >= ?' => $page->lft,
                    'lft <= ?' => $page->rht,
        ));

        $this->getAdapter()->update($this->_prefix . 'page',
                array(
                    'rht' => new Zend_Db_Expr('rht - 2'),
                ),
                array(
                    'rht > ?' => $page->rht,
        ));

        $this->getAdapter()->update($this->_prefix . 'page',
                array(
                    'lft' => new Zend_Db_Expr('lft - 2'),
                ),
                array(
                    'lft > ?' => $page->rht,
        ));
    }

    public function getTree() {
        try {
            $root = $this->find(1)->current();
            $select = $this->getAdapter()
                            ->select('*')
                            ->from($this->_name)
                            ->where('lft BETWEEN ' . $root->lft . ' AND ' . $root->rht)
                            ->where('id <> 1')->order('lft ASC')
                            ->where('language = ?', $this->_lang);
            $rs = $select->query()->fetchAll();
            return new Tomato_Model_RecordSet($rs, $this);
        } catch (Exception $ex) {
            echo $ex->getMessage();
            return null;
        }
    }

    public function getParents($pageId) {
        $rs = $this->_conn
                        ->select()
                        ->from(array('node' => $this->_prefix . 'page'), array())
                        ->from(array('parent' => $this->_prefix . 'page'))
                        ->where('node.lft BETWEEN parent.lft AND parent.rht')
                        ->where('node.page_id = ?', $pageId)
                        ->order('parent.lft')
                        ->query()
                        ->fetchAll();
        return new Tomato_Model_RecordSet($rs, $this);
    }

    /* ========== For translation =========================================== */

    public function getTranslations($item) {
        
        $rs = $this->getAdapter()
                        ->select()
                        ->from(array('p' => $this->_prefix . 'page'))
                        ->joinInner(array('tr' => $this->_prefix . 'core_translation'),
                                'tr.item_class = ?
						AND (tr.item_id = ? OR tr.source_item_id = ?)
						AND (tr.item_id = p.id OR tr.source_item_id = p.id)',
                                array('tr.source_item_id'))
                        ->group('p.id')
                        ->bind(array(
                            'Page_Models_Entities_Page',
                            $item->id,
                            $item->id,
                        ))
                        ->query()
                        ->fetchAll(); 
        return (null == $rs) ? null : new Tomato_Model_RecordSet($rs, $this);
    }

    public function getTranslatable($lang) {
        $sql = 'SELECT p.*, (tr.item_id IS NULL) AS translatable
				FROM
				(
					SELECT node.id, node.name, node.slug, (COUNT(parent.name) - 1) AS depth, 
						node.lft, node.rht, node.parent_id
					FROM ' . $this->_prefix . 'page AS node, 
						' . $this->_prefix . 'page AS parent
					WHERE node.lft BETWEEN parent.lft AND parent.rht
						AND node.language = ?
						AND parent.language = ?
					GROUP BY node.id
					ORDER BY node.lft
				) AS p
				LEFT JOIN ' . $this->_prefix . 'core_translation AS tr
					ON tr.source_item_id = p.id
					AND tr.item_class = ?
					AND tr.source_language = ?
					AND tr.language = ?';

        $rs = $this->getAdapter()
                        ->query($sql,
                                array(
                                    $this->_lang, $this->_lang,
                                    'Page_Models_Entities_Page',
                                    $this->_lang, $lang
                        ))
                        ->fetchAll();
        
        return new Tomato_Model_RecordSet($rs, $this);
    }

    public function getSource($page) {
        try{
            $row = $this->getAdapter()
                        ->select()
                        ->from(array('p' => $this->_prefix . 'page'))
                        ->joinInner(array('tr' => $this->_prefix . 'core_translation'), 'p.id = tr.source_item_id', array())
                        ->where('tr.item_id = ?', $page->id)
                        ->where('tr.item_class = ?', 'Page_Models_Entities_Page')
                        ->limit(1)
                        ->query()
                        ->fetch();

            return (null == $row) ? null : new Page_Models_Entities_Page($row);
        }catch(Exception $ex){
            echo $ex->getMessage();
        }
    }

}
